﻿using System.Linq;
using DataAccess.Accessors.Interfaces;
using DataAccess.DAO;
using NHibernate.Linq;

namespace DataAccess.Accessors
{
    public class UserAccessor : IUserAccessor
    {
        private readonly IDataAccessor _dataAccessor;

        public UserAccessor(IDataAccessor dataAccessor)
        {
            _dataAccessor = dataAccessor;
        }

        public UserDAO GetUser(string userName)
        {
            using (var session = _dataAccessor.OpenNHibernateSession())
            {
                return (from users in session.Query<UserDAO>()
                        where users.UserName == userName
                        select users).SingleOrDefault();
            }
        }

        public UserDAO GetUser(string userName, string password)
        {
            using (var session = _dataAccessor.OpenNHibernateSession())
            {
                return (from users in session.Query<UserDAO>()
                        where users.UserName == userName
                        && users.Password == password
                        select users).SingleOrDefault();
            }
        }

        public UserDAO SaveNewUser(UserDAO newUser)
        {
            using (var session = _dataAccessor.OpenNHibernateSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    session.SaveOrUpdate(newUser);
                    transaction.Commit();
                }
            }
            return newUser;
        }
    }
}
